package com.hrms.controller.admin;

import com.hrms.entity.Employee;
import com.hrms.http.ResponseResult;
import com.hrms.service.EmployeeService;
import com.hrms.utils.EntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Transactional
@RestController
@RequestMapping("/admin/employeemanage/newemployee")
public class AdminNewEmployeeController {
    // 管理员新建员工

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/add")
    public ResponseResult<Object> add(@RequestBody EntityUtil entity) {
        // 新建员工
        Employee employee = new Employee();
        employee.setEmployee_id(entity.getEmployee_id());
        employee.setEmployee_name(entity.getEmployee_name());
        employee.setEmployee_password(entity.getEmployee_password());
        employee.setEmployee_status("离线");

        // 工号已存在
        if(employeeService.idExist(employee)) {
            // 回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseResult<>("ERROR_employee_id", null);
        }

        // 新建员工
        if(!employeeService.add(employee)) {
            // 回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseResult<>("ERROR", null);
        }

        return new ResponseResult<>("SUCCESS", null);
    }
}
